'use strict';

module.exports = (app) => {
  class CarouselService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { CarouselGroup, ProjectAdmin, Carousel, Admin } =
        app.model.Tables.Web;
      const data = ctx.request.body;
      // 获取token
      // const token = ctx.get('authorization');
      // const adminRes = await Admin.findOne({
      //   where: {
      //     access_token: token,
      //   },
      // });
      // 根据token查找项目id
      // const projectRes = await ProjectAdmin.findOne({
      //   where: {
      //     adminId: adminRes.dataValues.id,
      //   },
      // });
      // 根据图片数组长度创建
      for (let i = 0; i < data.carouselArr.length; i++) {
        await Carousel.create({
          url: data.carouselArr[i],
          carouselGroupId: data.carouselGroupId,
          projectId: ctx.adminInfo.project_id,
        });
      }
      return '创建成功';
    }

    async delete() {
      const { app, ctx } = this;
      const { Carousel } = app.model.Tables.Web;
      const query = ctx.params;
      const res = await Carousel.destroy({
        where: {
          id: query.id,
          projectId: ctx.adminInfo.project_id,
        },
      });
      if (res) {
        return '删除成功';
      }
      return 'id不存在,删除失败';
    }

    async get() {
      const { app, ctx } = this;
      const { Carousel } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await Carousel.findOne({
        where: {
          id: data.id,
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
      });
      return res;
    }

    async getAll() {
      const { app, ctx } = this;
      const { Carousel } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await Carousel.findAndCountAll({
        where: {
          projectId: ctx.adminInfo.project_id,
        },
      });

      return res;
    }

    async update() {
      const { app, ctx } = this;
      const { Carousel } = app.model.Tables.Web;
      const { id } = ctx.params;
      const data = ctx.request.body;

      const res = await Carousel.update(data, {
        where: {
          id,
          projectId: ctx.adminInfo.project_id,
        },
      });

      return res;
    }
  }
  return CarouselService;
};
